import React, { useState, useContext, useEffect } from 'react';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import ImgCrop from 'antd-img-crop';
import { UploadContext } from '../uploadContext';
import axios from 'axios';

const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('上传头像的格式只能是jpg/png!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('头像大小必须小于2MB!');
    }
    return isJpgOrPng && isLt2M;
};

const Uptou = ({ onAvatarUpdate, imageUrl, setImageUrl }) => {
    const [loading, setLoading] = useState(false);
    const { startUpload, endUpload } = useContext(UploadContext);
    const [userInfo, setUserInfo] = useState(null);

    useEffect(() => {
        const userInfoString = localStorage.getItem('user');
        if (userInfoString) {
            try {
                const parsedUserInfo = JSON.parse(userInfoString);
                setUserInfo(parsedUserInfo);
                if (parsedUserInfo && parsedUserInfo.tou_img) {
                    setImageUrl(parsedUserInfo.tou_img);
                }
            } catch (error) {
                console.error('Error parsing user info from localStorage:', error);
            }
        }
    }, [setImageUrl]);

    const handleChange = async (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true); // 上传过程中显示加载状态
            const formData = new FormData();
            formData.append('filessss', info.file.originFileObj);

            try {
                const response = await axios.post('http://localhost:3001/uploads', formData, {
                    headers: {
                        'Content-Type': 'multipart/form-data',
                        'Authorization': `Bearer ${userInfo.token}`, // 假设userInfo中包含用户token
                        'userId': userInfo.id // 将用户ID通过header传递
                    }
                });

                const data = response.data;
                message.success('头像上传成功！');
                setLoading(false);
                endUpload(); // 调用结束上传的context方法

                // 设置imageUrl为本地预览
                const reader = new FileReader();
                reader.onload = () => {
                    setImageUrl(reader.result);
                    onAvatarUpdate(reader.result);
                };
                reader.readAsDataURL(info.file.originFileObj);

                // 更新userInfo的tou_img属性，并同步到localStorage
                if (userInfo) {
                    const updatedUserInfo = { ...userInfo, tou_img: data.url }; // 假设后端返回的响应中包含新头像的URL
                    setUserInfo(updatedUserInfo); // 更新userInfo状态
                    setImageUrl(data.url); // 更新imageUrl状态
                    localStorage.setItem('user', JSON.stringify(updatedUserInfo)); // 同步更新localStorage
                }
            } catch (error) {
                console.error('错误:', error);
                message.error('头像上传失败，请重试！');
                setLoading(false);
            }
        } else if (info.file.status === 'error') {
            setLoading(false); // 上传错误，设置加载状态为 false
            console.error('头像上传失败:', info.file.response);
            message.error('头像上传失败，请重试！'); // 显示错误消息
        }
    };

    const uploadButton = (
        <button
            style={{
                border: 0,
                background: 'none',
            }}
            type="button"
        >
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div
                style={{
                    marginTop: 8,
                }}
            >
                上传头像
            </div>
        </button>
    );

    return (
        <ImgCrop modalOk={'完成'} modalCancel={'取消'} rotationSlider>
            <Upload
                name="avatar"
                listType="picture-circle"
                className="avatar-uploader"
                showUploadList={false}
                beforeUpload={beforeUpload}
                onChange={handleChange}
            >
                {imageUrl ? (
                    <img
                        src={imageUrl.startsWith('http') ? imageUrl : `http://localhost:3001/images/${imageUrl}`}
                        alt="avatar"
                        style={{
                            width: '100%',
                            borderRadius: '50%',
                        }}
                    />
                ) : (
                    uploadButton
                )}
            </Upload>
        </ImgCrop>
    );
};

export default Uptou;
